package org.jeecg.modules.demo.jxcx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.dto.OpenidAccountDTO;
import org.jeecg.modules.demo.jxcx.mapper.JxcUserMapper;
import org.jeecg.modules.demo.jxcx.po.JxcUser;
import org.jeecg.modules.demo.jxcx.po.SystemVo;
import org.jeecg.modules.demo.jxcx.service.ITbPayOrdidService;
import org.jeecg.modules.demo.jxcx.service.JxcOpenuserService;
import org.jeecg.modules.demo.jxcx.service.JxcUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
* @author DeskTop
* @description 针对表【jxc_user】的数据库操作Service实现
* @createDate 2024-07-23 17:17:19
*/
@Service
public class JxcUserServiceImpl extends ServiceImpl<JxcUserMapper, JxcUser>
implements JxcUserService{
    private static Logger logger = LoggerFactory.getLogger(JxcUserServiceImpl.class);
    @Value("${wxApp.appId}")
    private String appId;

    @Value("${wxApp.appSecret}")
    private String appSecret;
    @Autowired
    private JxcOpenuserService jxcOpenuserService;
    @Autowired
    private JxcUserMapper jxcUserMapper;
    @Autowired
    private ITbPayOrdidService iTbPayOrdidService;
    @Override
    public JSONObject getOpenid(SystemVo systemVo) throws Exception {
        String code = systemVo.getCode();
        String getOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        logger.info(getOpenIdUrl);

        HttpClient httpClients = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(getOpenIdUrl);
        ResponseHandler responseHandler = new BasicResponseHandler();

        String responseBody = (String) httpClients.execute(httpGet, responseHandler);
        logger.info("=========================获取token===================");
        logger.info(responseBody);
        JSONObject jsonObject = JSON.parseObject(responseBody);
        if (StringUtils.isEmpty(jsonObject.getString("openid"))){
            throw new Exception("未获取到openid，请重新进入小程序");
        }
        OpenidAccountDTO openidAccountDTO = this.queryDefault(jsonObject.getString("openid"));
        JSONObject result = new JSONObject();
        if (openidAccountDTO == null){
            result.put("code",500);
            result.put("msg","没有账号记录");
            result.put("openid",jsonObject.getString("openid"));
            return result;
        }
        String isDefult = openidAccountDTO.getIsDefult();

        if (isDefult.equals("1")){
            JSONObject infor = new JSONObject();
            result.put("code",200);
            infor.put("account",openidAccountDTO.getAccount());
            infor.put("name",openidAccountDTO.getName());
            infor.put("companyId",openidAccountDTO.getCompanyId());
            infor.put("id",openidAccountDTO.getId());
            infor.put("phone",openidAccountDTO.getPhone());
            infor.put("other",openidAccountDTO.getOther());
            infor.put("otherid",openidAccountDTO.getOtherid());
            infor.put("ivcode",openidAccountDTO.getIvcode());
            infor.put("ivmoney",openidAccountDTO.getIvmoney());
            infor.put("ivnum",openidAccountDTO.getIvnum());
            infor.put("jurisdiction",openidAccountDTO.getJurisdiction());
            infor.put("exdate",openidAccountDTO.getExdate());
            infor.put("beizhu",openidAccountDTO.getBeizhu());
            result.put("infor",infor);

            result.put("openid",openidAccountDTO.getOpenid());
            return result;
        }else {
            result.put("code",500);
            result.put("msg","未登录");
            result.put("openid",openidAccountDTO.getOpenid());
            return result;
        }

    }
    @Override
    public OpenidAccountDTO queryDefault(String openid) throws Exception {
        if (openid.isEmpty()) {
            throw new Exception("查询默认就诊人失败，openid不能为空");
        }
        //查询本地默认就诊人信息
        OpenidAccountDTO openidAccountDTO = jxcOpenuserService.queryDefaultByOpenid(openid);
        logger.info("查询本地默认就诊人信息：" + openidAccountDTO);
        return openidAccountDTO;
    }

    @Override
    public JxcUser getByAccount(String account) {
        return jxcUserMapper.getByAccount(account);
    }

    @Override
    public List<JxcUser> getByConpanyId(String companyId) {
        return jxcUserMapper.getCostsByCompanyId(companyId);
    }

    @Override
    public JxcUser getByivcode(String ivcode) {
        return baseMapper.getByivcode(ivcode);
    }
    @Override
    public R exdate(JSONObject json) {
        String id = json.getString("id");
        JxcUser jxcUser = getById(id);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime otherDate = LocalDateTime.parse(jxcUser.getExdate(), formatter);
        String datetype = json.getString("datetype");
        logger.info(jxcUser.toString() +"账号续费:"+datetype);
        if (datetype.equals("一季度")){
            LocalDateTime exdate = otherDate.plusDays(93); // 加上93天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("半年")){
            LocalDateTime exdate = otherDate.plusDays(183); // 加上183天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("一年")){
            LocalDateTime exdate = otherDate.plusDays(365); // 加上365天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("两年")){
            LocalDateTime exdate = otherDate.plusDays(730); // 加上365天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("三年")){
            LocalDateTime exdate = otherDate.plusDays(1095); // 加上365天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("一个月")){
            LocalDateTime exdate = otherDate.plusDays(31);
            jxcUser.setExdate(exdate.format(formatter));
        }
        return new R().ok(updateById(jxcUser));
    }

    @Override
    public R add(JSONObject json) {
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 格式化当前的日期和时间
        String formattedDateTime = now.format(formatter);
        String id = now.format(formatter2);
//        id = "1"+String.valueOf((int)(Math.random()*900000+100000))+id;

        String datetype = json.getString("datetype");
        JxcUser jxcUser = new JxcUser();
        jxcUser.setAccount(json.getString("account"));
        jxcUser.setCompanyId(json.getString("companyId"));
        jxcUser.setName(json.getString("name"));
        jxcUser.setPassword(json.getString("password"));
        jxcUser.setPhone(json.getString("phone"));
        jxcUser.setOther(formattedDateTime);
        jxcUser.setId(Long.valueOf(id));
        LocalDateTime otherDate = LocalDateTime.parse(formattedDateTime, formatter);
        if (datetype.equals("一季度") || datetype.equals("季度特惠")){
            LocalDateTime exdate = otherDate.plusDays(93); // 加上93天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("半年")){
            LocalDateTime exdate = otherDate.plusDays(183); // 加上183天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("一年") || datetype.equals("年度特惠")){
            LocalDateTime exdate = otherDate.plusDays(365); // 加上365天
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("一个月") || datetype.equals("单月特惠") || datetype.equals("单月体验")){
            LocalDateTime exdate = otherDate.plusDays(30);
            jxcUser.setExdate(exdate.format(formatter));
        }else if (datetype.equals("注册体验")){
            LocalDateTime exdate = otherDate.plusMinutes(30);
            jxcUser.setExdate(exdate.format(formatter));
        }
        // 如果有邀请码
        if (StringUtils.isNotBlank(json.getString("ivcode"))){
            JxcUser j = getByivcode(json.getString("ivcode"));
            String ivnum = j.getIvnum();
            j.setIvnum(String.valueOf(Integer.parseInt(ivnum)+1));
            updateById(j);
        }
        // 生成邀请码
        String ivcode = String.valueOf((int) (Math.random() * 900000 + 100000));
        JxcUser j1 = getByivcode(ivcode);
        if (j1 != null){
            ivcode = String.valueOf((int) (Math.random() * 900000 + 100000));
            jxcUser.setIvcode(ivcode);
        }else {
            jxcUser.setIvcode(ivcode);
        }
        jxcUser.setIvnum("0");
        jxcUser.setIvmoney("0");
        jxcUser.setJurisdiction(json.getString("jurisdiction"));
        logger.info("注册账户："+jxcUser.toString());
        return new R().ok(save(jxcUser));
    }
    @Override
    public R DXFW(JSONObject params) throws Exception {
        String mobile = params.getString("phone");
        Random random = new Random();
        // 生成100000到999999之间的随机整数（包括100000，不包括1000000）
        int i = 1000 + random.nextInt(9000);
        //将数字转为字符串
        String code = String.valueOf(i);
        logger.info("手机号"+mobile+"验证码"+code);
        if(StringUtils.isBlank(iTbPayOrdidService.selectMobile(mobile))) {
            iTbPayOrdidService.savedxyzm(mobile, code, "0");
        }else {
            iTbPayOrdidService.updatedxyzm(mobile, code, "0");
        }
//        senddx(mobile, code);
        return new R().ok("发送成功");
    }

    @Override
    public R YZMYZ(JSONObject params) {
        String mobile = params.getString("phone");
        String code = params.getString("code");
        if(iTbPayOrdidService.selectCodeByMobile(mobile, code).equals(code)) {
            iTbPayOrdidService.updatedxyzm(mobile, "0", "1");
            return new R().ok("验证码正确");
        }else {
            return new R().error("验证码错误");
        }
    }

    @Override
    public R companyisregister(JSONObject params) {
        String companyId = params.getString("companyId");
        List<JxcUser> list = getByConpanyId(companyId);
        if (list.size() == 0){
            return new R().ok("未注册");
        }else {
            return new R().error("已注册");
        }
    }
    @Override
    public R ivcodeisregister(JSONObject params) {
        String ivcode = params.getString("ivcode");
        JxcUser jxcUser = getByivcode(ivcode);
        if (jxcUser != null){
            return new R().ok("邀请码合格");
        }else {
            return new R().error("邀请码不存在");
        }
    }

    @Override
    public JxcUser getByphone(String phone) {
        return baseMapper.getByphone(phone);
    }

//    public List<JxcUser> getByIvcode(String ivcode) {
//        return jxcUserMapper.getByivcode(ivcode);
//    }

//    public void senddx(String number, String code) throws Exception {
//        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
//                .accessKeyId("LTAI5tEHMSyUYupW6hK6HXAK")
//                .accessKeySecret("9ELZP9hhm1TzixfO7h6wl42tnLtGmP")
//                .build());
//
//        // Configure the Client
//        AsyncClient client = AsyncClient.builder()
//                .region("cn-hangzhou") // Region ID
//                .credentialsProvider(provider)
//                .overrideConfiguration(
//                        ClientOverrideConfiguration.create()
//                                .setEndpointOverride("dysmsapi.aliyuncs.com")
//                )
//                .build();
//        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
//                .signName("睿创软件技术")
////                .templateCode("SMS_472370375")
//                .templateCode("SMS_305050339")
//                .phoneNumbers(number)
//                .templateParam("{\"code\":\""+code+"\"}")
//                .build();
//        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
//        SendSmsResponse resp = response.get();
//        System.out.println(new Gson().toJson(resp));
//        client.close();
//    }
}
